<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            clearable
            @clear="getUserList"
            placeholder="请输入内容"
            v-model="queryInfo.query"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisiable = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="~"></el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              @change="userStateChange(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
              v-model="scope.row.mg_state"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot='scope'>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="编辑角色"
              placement="top"
            >
              <el-button
               @click="showEditDialog(scope.row.id)"
                size="mini"
                type="primary"
                icon="el-icon-edit"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
            >
              <el-button
                @click="removeUserById(scope.row.id)"
                size="mini"
                type="danger"
                icon="el-icon-delete"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisiable" width="50%" @close="DiglogClose">
      <!-- 内容主题 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username"></el-input>
      </el-form-item>
       <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password"></el-input>
      </el-form-item>
        <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email"></el-input>
      </el-form-item>
       <el-form-item label="手机号" prop="mobile">
      <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
    </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog
      @close="editDialogClose"
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      >
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close='setRoleDialogClosed'
      >
      <div>
        <p>当前用户: {{userInfo.username}}</p>
        <p>当前角色: {{userInfo.role_name}}</p>
        <p>分配角色
          <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  components: {},
  created() {
    this.getUserList();
  },
  data() {
    // 验证规则
    let checkEmail = (rule, value, callback) => {
      let regEmail = new RegExp("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$");
      if(regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    let checkMobile = (rule, value, callback) => {
       let regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if(regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      // 分配角色的对话框的显示隐藏
      setRoleDialogVisible: false,
      //分配角色的用户信息
      userInfo: {},
      // 分配角色的数据列表
      rolesList: [],
      selectedRoleId: '',
      editForm: {},
      editDialogVisible: false,
      userList: [],
      total: 0,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
          ],  
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],  
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
           { validator: checkMobile, trigger: 'blur' }
        ], 
      },
      // 对话框的显示隐藏
      addDialogVisiable: false,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
    };
  },
  methods: {
    //获取用户数据
    async getUserList() {
      const { data: res } = await this.$request({
        url: "users",
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    //pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;

      this.getUserList();
    },
    //页码改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    //用户状态修改
    async userStateChange(info) {
      const { data: res } = await this.$request({
        url: `users/${info.id}/state/${info.mg_state}`,
        method: "put",
      });
      if (res.meta.status !== 200)
        return this.$message.error("更新用户状态失败");
      this.$message.success("更新用户状态成功");
    },
    //监听用户对话框的关闭事件
    DiglogClose() {
      this.$refs.addFormRef.resetFields()
    },
    //添加用户预校验
    addUser() {
      this.$refs.addFormRef.validate( async (valid, result) => {
        if(!valid) return this.$message.error('信息错误，无法添加')
        //网络请求添加用户
        const { data: res } = await this.$request({
          url: 'users',
          method: 'post',
          data: this.addForm
        })
        if(res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 成功后隐藏对话框
        this.addDialogVisiable = false
        //添加成功后重新获取列表数据
        this.getUserList();
      })
    },
    //展示用户编辑对话框
    async showEditDialog(id) {
      this.editDialogVisible = !this.editDialogVisible;
      const { data: res } = await this.$request({
          url: `users/${id}`
        })
        if(res.meta.status !== 200) return this.$message.error('查询用户信息失败')
        this.editForm = res.data
    },
    // 重置修改的对话框
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 提交修改后的用户信息
    editUser(id) {
      this.$refs.editFormRef.validate( async valid => {
        if(!valid) return this.$message.error('信息错误，无法修改')
        //无误，发送请求
        const { data: res} = await this.$request({
          url: `users/${this.editForm.id}`,
          method: 'put',
          data: this.editForm
        })
        if(res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改成功')
        this.getUserList()
        this.editDialogVisible = !this.editDialogVisible;
      })
    },
    //删除用户弹出框
    async removeUserById(id) {
      try {
        const res = await this.$confirm('此操作将永久删除该用户, 确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        const { data: deleteResult } = await this.$request({
          url: `users/${id}`,
          method: 'delete'
        })
        if(deleteResult.meta.status !== 200) return this.$message.error('删除用户失败')
        this.getUserList()
        this.$message.success('已删除成功')
      } catch(err) {
        return this.$message.info('已取消删除')
      }
    },
    //分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      // 展开对话框前获取所有角色列表
      const { data: res } = await this.$request({
          url: `roles`,
        })  
        if(res.meta.status !== 200) return this.$message.error('请求角色列表失败')
        this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 点击后分配角色
    async saveRoleInfo() {
      if(!this.selectedRoleId) return this.$message.error('请选择分配的角色')
      const { data: res } = await this.$request({
          url: `users/${this.userInfo.id}/role`,
          method: 'put',
          data: {rid: this.selectedRoleId}
        })  
        if(res.meta.status !== 200) return this.$message.error('请求角色列表失败')
        this.$message.success('更新角色成功')
        this.getUserList()
        this.setRoleDialogVisible = false;
    },
    //关闭分配角色对话框关闭后情况数据
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = ''
    }
  },
};
</script>

<style lang="less" scoped></style>
